<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="moduleFormRef"
      :model="form"
      :rules="rules"
      label-width="160px"
    >
      <el-form-item :label="$t('sysModule.code')" prop="moduleCode">
        <el-input
          v-model="form.moduleCode"
          :placeholder="$t('sysModule.codeRequired')"
          :disabled="(form as ModuleUpdateReq).moduleId ? true : false"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('sysModule.name')" prop="moduleName">
        <el-input
          v-model="form.moduleName"
          :placeholder="$t('sysModule.nameRequired')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('sysModule.description')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :autosize="{ minRows: 2 }"
          :placeholder="$t('sysModule.descriptionRequired')"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import type {
  ModuleFormReq,
  ModuleKey,
  ModuleUpdateReq,
} from "@/api/system/module/types";
import { moduleApi } from "@/api/system/module/index";

const props = defineProps({
  entityKey: {
    type: Object as PropType<ModuleKey>,
    default: () => {},
  },
});
const model = defineModel<boolean>();
const moduleFormRef = ref<FormInstance>();
let form = reactive<ModuleFormReq>({
  updateMask: "moduleCode,moduleName,description",
  requestId: Math.random() * 10 + "",
});

// 修改模块编码时，检查编码是否重复
const moduleCodeValidate = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("sysModule.codeRequired")));
  } else {
    if (!(form as ModuleUpdateReq).moduleId) {
      moduleApi.checkModuleApi(value).then(({ data }) => {
        if (data === true) {
          callback(new Error("该编码已存在"));
        } else {
          callback();
        }
      });
    } else {
      callback();
    }
  }
};

const rules = reactive<FormRules<ModuleFormReq>>({
  moduleCode: [
    { required: true, validator: moduleCodeValidate, trigger: "blur" },
  ],
  moduleName: [
    { required: true, message: t("sysModule.nameRequired"), trigger: "blur" },
  ],
});
const emits = defineEmits(["refresh"]);

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  moduleApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
  });
}

const submitForm = async () => {
  await moduleFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        moduleApi.update(form as ModuleUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        moduleApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
